/**
 * -----------------------------------------------------------------
 * 状态模式实例
 */

// 状态(各种灯)
class State {
  constructor(color) {
    this.color = color
  }
  handle(context) {
    console.log(`trun to ${this.color} light`)
    context.setState(this)
  }
}

// 主题
class Context {
  constructor() {
    this.state = null
  }
  getState() {
    return this.state
  }
  setState(state) {
    this.state = state
  }
}

let context = new Context()
let green = new State('green')
let red = new State('red')
let yellow = new State('yellow')

// 绿灯亮了
// green.handle(context)
// console.log(context.getState())

// yellow.handle(context)
// console.log(context.getState())

// red.handle(context)
// console.log(context.getState())

import StateMachine from 'javascript-state-machine'
/**
 * -----------------------------------------------------------------
 * 有限状态机实例
 */

let fsm = new StateMachine({
  init: '收藏',
  transitions: [
    {
      name: 'doStore',
      form: '收藏',
      to: '取消收藏'
    },
    {
      name: 'deleteStore',
      form: '取消收藏',
      to: '收藏'
    }
  ],
  methods: {
    // 监听收藏
    onDoStore: function() {
      alert('收藏成功')
      updateText()
    },
    onDeleteStore: function() {
      alert('已经取消收藏')
      updateText()
    }
  }
})

let btnEl = document.getElementById("btn")

btnEl.onclick = function() {
  // console.log(fsm.state)
  if (fsm.is('收藏')) {
    fsm.doStore()
  } else {
    fsm.deleteStore()
  }
}

// 更新按钮文案
function updateText() {
  btnEl.innerHTML = fsm.state
}

// 初始化文案
updateText()


/**
 * -----------------------------------------------------------------
 * 简易promise
 */

class MyPromise {
  constructor(fn) {
    var successList = []
    var failList = []

    fn(function() {
      console.log("inResove")
    }, function() {
      console.log("inReject")
    })
  }
  then() {
    
  }
}

function loadImg (src) {
  new MyPromise(function(resolve, reject) {
    setTimeout(function() {
      resolve()
      console.log("2s后")
    }, 2000)
  })
}

loadImg()